package com.chenss.dragonserapp.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chenss.dragonserapp.R;
import com.chenss.dragonserapp.activity.CouponsActivity;
import com.chenss.dragonserapp.activity.MoneyRecordActivity;
import com.chenss.dragonserapp.activity.PostalActivity;
import com.chenss.dragonserapp.activity.QrPicActivity;
import com.chenss.dragonserapp.activity.ServiceInfoActivity;
import com.chenss.dragonserapp.activity.SettingsActivity;
import com.chenss.dragonserapp.app.AppInfo;
import com.chenss.dragonserapp.app.Constant;
import com.chenss.dragonserapp.base.BaseFragment;
import com.chenss.dragonserapp.model.ServiceInfoModel;
import com.chenss.dragonserapp.network.NetworkRequest;
import com.chenss.dragonserapp.network.RequestCallbcak;
import com.chenss.dragonserapp.response.MineInfoResponse;
import com.chenss.dragonserapp.utils.GsonUtil;
import com.chenss.dragonserapp.utils.ToastUtil;
import com.chenss.dragonserapp.view.CircularImage;

import org.json.JSONException;

import java.text.DecimalFormat;
import java.util.Set;
import java.util.logging.Logger;

/**
 * PageName:
 * Create by chenss at 2018/4/21 14:32
 */
public class ServiceFragment extends BaseFragment  implements RequestCallbcak {
    TextView tv_page_title;
    TextView tv_right;
    TextView tv_tixian;//提现
    LinearLayout ll_ser_record, ll_ser_set, ll_ser_contact , ll_ser_coupons;
LinearLayout ll_top_content;
    // 声明PopupWindow
    private PopupWindow popupWindow;
    // 声明PopupWindow对应的视图
    private View popupView;

    // 声明平移动画
    private TranslateAnimation animation;

    public NetworkRequest networkRequest;//网络请求
    public ArrayMap<String, String> parmMap;//请求参数封装
    ServiceInfoModel model;//serviceinfo对象
    String servicePhone="";//服务电话

    CircularImage img_head;//头像
    TextView tv_ser_phone,tv_money,tv_seal,tv_store_name;
    String store_wallet="0";//账户余额
    @Override
    public int bindLayout() {
        return R.layout.frag_tab_service;
    }
    boolean isEnter=false;
    @Override
    public void initView(View view) {
        tv_page_title = findView(view, R.id.tv_page_title);
        tv_right = findView(view, R.id.tv_right);
        tv_page_title.setText("服务中心");
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setOnClickListener(this);
        tv_right.setText("收钱");

        tv_tixian = findView(view, R.id.tv_tixian);
        tv_ser_phone = findView(view, R.id.tv_ser_phone);
        tv_money = findView(view, R.id.tv_money);
        tv_seal = findView(view, R.id.tv_seal);
        tv_store_name = findView(view, R.id.tv_store_name);
        img_head = findView(view, R.id.img_head);



        ll_top_content = findView(view, R.id.ll_top_content);
        ll_ser_record = findView(view, R.id.ll_ser_record);
        ll_ser_set = findView(view, R.id.ll_ser_set);
        ll_ser_contact = findView(view, R.id.ll_ser_contact);
        ll_ser_coupons = findView(view, R.id.ll_ser_coupons);
        tv_tixian.setOnClickListener(this);
        ll_top_content.setOnClickListener(this);
        ll_ser_record.setOnClickListener(this);
        ll_ser_set.setOnClickListener(this);
        ll_ser_contact.setOnClickListener(this);
        ll_ser_coupons.setOnClickListener(this);
    }

    @Override
    public void doBusiness(Context mContext) {
        networkRequest = new NetworkRequest(getActivity(),this);
        getStoreInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(isEnter){
            isEnter=false;
            getStoreInfo();
        }

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right:
                showQrPrice();
                break;
            case R.id.ll_top_content:
                if(null!=model){
                    isEnter=true;
                   Intent mIntent=new Intent(getActivity(),ServiceInfoActivity.class);
                   mIntent.putExtra("serviceInfo",model);
                   startActivity(mIntent);
                }else{
                    ToastUtil.showShort(getActivity(),"未获取到服务中心信息");
                }

                break;
             case R.id.tv_tixian:
                 if(!TextUtils.isEmpty(store_wallet)&&Double.parseDouble(store_wallet)>0){
                     isEnter=true;
                     Intent mIntent=new Intent(getActivity(),PostalActivity.class);
                     mIntent.putExtra("money",store_wallet);
                     startActivity(mIntent);
                 }else{
                     ToastUtil.showShort(getActivity(),"您的余额不足，无法提现");
                 }

                break;
            case R.id.ll_ser_record:
                isEnter=true;
                startActivity(MoneyRecordActivity.class);
                break;
            case R.id.ll_ser_set:
                isEnter=true;
                startActivity(SettingsActivity.class);
                break;
            case R.id.ll_ser_contact:
                if(!TextUtils.isEmpty(servicePhone)){
                    initPopupWindow();
                    lightoff();
                }

                break;
            case R.id.ll_ser_coupons:
                startActivity(CouponsActivity.class);
                break;
        }
    }

    protected void initPopupWindow(){
        if (popupWindow == null) {
            popupView = View.inflate(getActivity(), R.layout.popu_sheet, null);
            // 参数2,3：指明popupwindow的宽度和高度
            popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            TextView item1=findView(popupView,R.id.tv_item1);
            final TextView item2=findView(popupView,R.id.tv_item2);
            TextView cancle=findView(popupView,R.id.tv_cancle);
            item1.setText("拨打电话");
            item2.setText(servicePhone);
            item1.setTextSize(12);
            item2.setTextColor(ContextCompat.getColor(getActivity(),R.color.textRed));

            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    lighton();
                }
            });

            // 设置背景图片， 必须设置，不然动画没作用
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setFocusable(true);

            // 设置点击popupwindow外屏幕其它地方消失
            popupWindow.setOutsideTouchable(true);

            // 平移动画相对于手机屏幕的底部开始，X轴不变，Y轴从1变0
            animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                    Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 0);
            animation.setInterpolator(new AccelerateInterpolator());
            animation.setDuration(200);


            item2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 拨号
                    Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + item2.getText().toString()));
                    startActivity(intent);
                    popupWindow.dismiss();
                    lighton();
                }
            });
            cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                    lighton();
                }
            });
        }

        // 在点击之后设置popupwindow的销毁
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
            lighton();
        }

        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        popupWindow.showAtLocation(mContextView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        popupView.startAnimation(animation);

    }
    /**
     * 设置手机屏幕亮度变暗
     */
    private void lightoff() {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.3f;
        getActivity().getWindow().setAttributes(lp);
    }

    /**
     * 设置手机屏幕亮度显示正常
     */
    private void lighton() {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 1f;
        getActivity().getWindow().setAttributes(lp);
    }
    /**
     * 获取信息
     */
    private void getStoreInfo() {
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Store, Constant.classes.GetStoreInfo);
        parmMap.put("store_id", AppInfo.getUser(getActivity()).getStore_id());//服务站用户id
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_1, true, Constant.classes.GetStoreInfo);
    }

    @Override
    public void onFaild(int orderCode, String result) {
        ToastUtil.showShort(getActivity(), result);
    }

    @Override
    public void onSucceed(int orderCode, String result) throws JSONException {
        Logger.getLogger(result);
        if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_1) {
            MineInfoResponse response = GsonUtil.GsonToBean(result,MineInfoResponse.class);
            if (null != response) {
                if (0 == response.getStatus()&&null!=response.getData()) {
                   model=response.getData().getStorehouse_info();
                    servicePhone=response.getData().getStore_phone();
                     tv_ser_phone.setText(servicePhone);
                    tv_money.setText("￥"+response.getData().getStore_wallet());
                    store_wallet=response.getData().getStore_wallet();
                    tv_seal.setText("￥"+response.getData().getOrder_total_money());
                    tv_store_name.setText(model.getStorehouse_name());
                    if(!TextUtils.isEmpty(response.getData().getAvatar_url()))
                    Glide.with(getActivity()).load(response.getData().getAvatar_url()).asBitmap().placeholder(R.mipmap.morentu).into(img_head);
                }


            }


        }
    }
    /**
     * 输入金额提示
     */
    protected void showQrPrice() {
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_image);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_input_price);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        final EditText edt = (EditText) dialog.findViewById(R.id.edt_price);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        Button btn_qx = (Button) dialog.findViewById(R.id.btn_one);
        Button btn_qd = (Button) dialog.findViewById(R.id.btn_two);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        if (!dialog.isShowing()) {
            dialog.show();
        }
        edt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        edt.setText(s);
                        edt.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edt.setText(s);
                    edt.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edt.setText(s.subSequence(0, 1));
                        edt.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        dialog.getWindow().setAttributes(params);

        btn_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        btn_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!TextUtils.isEmpty(edt.getText().toString())&&edt.getText().toString().length()>0) {
//                    ToastUtil.showShort(MainActivity.this, "提交成功");
                    if(edt.getText().toString().startsWith(".")||edt.getText().toString().endsWith(".")){
                        ToastUtil.showShort(getActivity(), "请输入正确的金额");
                        return;
                    }
                    dialog.dismiss();
                    DecimalFormat decimalFormat =new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String price = decimalFormat.format(Double.parseDouble(edt.getText().toString()));//format 返回的是字符串
                    isEnter=true;
                    Intent m=new Intent(getActivity(),QrPicActivity.class);
                    m.putExtra("price",price);
                    startActivity(m);
                } else {
                    ToastUtil.showShort(getActivity(), "请输入金额");
                }
            }
        });

    }
}
